<template>
  <div class="app-container">
    <h1 style="margin-top">视频滤镜</h1>
    <video id="video" autoplay controls ref="myVideo"></video>
    <div class="btn-group">
      <el-button type="primary" size="small" @click="openVideoFilter"
        >打开摄像头</el-button
      >
      <el-button type="primary" size="small" @click="closeVideoFilter"
        >关闭摄像头</el-button
      >
      <el-button type="primary" size="small" @click="onBlur"
        >模糊滤镜</el-button
      >
      <el-button type="primary" size="small" @click="onGrey"
        >灰度滤镜</el-button
      >
      <el-button type="primary" size="small" @click="onInvert"
        >反转滤镜</el-button
      >
      <el-button type="primary" size="small" @click="onSepia"
        >深褐色滤镜</el-button
      >
    </div>
  </div>
</template>
<script>
import { defineComponent, reactive, toRefs, ref } from "vue";

export default defineComponent({
  setup() {
    const myVideo = ref(null);
    const constraints = (window.constraints = {
      audio: false,
      video: true,
    });
    const state = reactive({
      stream: {},
      videoTracks: [],
    });
    const openVideoFilter = async () => {
      try {
        state.stream = await navigator.mediaDevices.getUserMedia(constraints);
        state.videoTracks = state.stream.getVideoTracks();
        handleSuccess();
      } catch (e) {
        console.log(e);
      }
    };
    const onBlur = () => {
      let video = document.getElementById("video");
      video.className = "blur";
    };
    const handleSuccess = () => {
      let video = document.getElementById("video");
      video.srcObject = state.stream;
    };
    const closeVideoFilter = () => {
      state.videoTracks[0].stop();
    };
    const onGrey = () => {
      let video = document.getElementById("video");
      video.className = "grey";
    };
    const onInvert = () => {
      let video = document.getElementById("video");
      video.className = "invert";
    };
    const onSepia = () => {
      let video = document.getElementById("video");
      video.className = "sepia";
    };
    return {
      ...toRefs(state),
      openVideoFilter,
      closeVideoFilter,
      onBlur,
      onGrey,
      onInvert,
      onSepia,
      myVideo,
    };
  },
});
</script>
<style scoped>
.app-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
#video {
  box-sizing: border-box;
  padding: 0 10px;
  width: 100%;
  height: 500px;
}
.btn-group {
  display: flex;
  flex-direction: row;
  margin-top: 10px;
}
/* 模糊滤镜 */
.blur {
  filter: blur(3px);
}
/* 灰度滤镜 */
.grayscale {
  filter: grayscale(1);
}
/* 反转 */
.invert {
  filter: invert(1);
}
/* 深褐色 */
.sepia {
  filter: sepia(1);
}
</style>
